package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.WebSocketGroupUser;
import com.ruoyi.teaching.domain.WebSocketUserDialogue;
import com.ruoyi.teaching.domain.vo.UserFriendVO;
import com.ruoyi.teaching.mapper.WebSocketGroupUserMapper;
import com.ruoyi.teaching.mapper.WebSocketMessageMapper;
import com.ruoyi.teaching.mapper.WebSocketUserApplicationMapper;
import com.ruoyi.teaching.mapper.WebSocketUserDialogueMapper;
import com.ruoyi.teaching.service.WebSocketUserDialogueService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李志鑫
 * @since 2024-08-23
 */
@Service
public class WebSocketUserDialogueServiceImpl extends ServiceImpl<WebSocketUserDialogueMapper, WebSocketUserDialogue> implements WebSocketUserDialogueService {
    @Autowired
    private WebSocketUserDialogueMapper webSocketUserDialogueMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WebSocketGroupUserMapper webSocketGroupUserMapper;

    @Autowired
    private WebSocketUserApplicationMapper webSocketUserApplicationMapper;


    @Autowired
    private WebSocketMessageMapper webSocketMessageMapper;
    @Override
    public AjaxResult getUserList(String message, Integer type) {
        QueryWrapper<WebSocketUserDialogue> webSocketUserDialogueQueryWrapper = new QueryWrapper<>();
        webSocketUserDialogueMapper.selectList(webSocketUserDialogueQueryWrapper);
        Integer userId = SecurityUtils.getUserId().intValue();
        String username = SecurityUtils.getUsername();
        System.out.println(username);
        if (null != type && type == 0) {
            webSocketUserDialogueQueryWrapper.eq("type", 0);//单聊
        } else if (null != type && type == 1) {
            webSocketUserDialogueQueryWrapper.eq("type", 1);//群聊
        } else if (null != type && type == 3) {
            webSocketUserDialogueQueryWrapper.eq("type", 3);//临时
        } else {
            return new AjaxResult(HttpStatus.ERROR, "类型错误暂未开发");
        }

        webSocketUserDialogueQueryWrapper.and(w -> w.eq("a_user_id", userId).or().eq("b_user_id", userId).or().apply(username != null, "FIND_IN_SET ('" + username + "',group_user)"));
//        if (null != message && !message.equals("")) {
//            webSocketUserDialogueQueryWrapper.like("a_user_name", message)
//                    .or().like("a_user_remarks", message)
//                    .or().like("b_user_name", message)
//                    .or().like("b_user_remarks", message)
//                    .or().like("group_name", message)
//                    .or().like("group_remarks", message);
//        }
        List<UserFriendVO> userFriendVOS = new ArrayList<>();
        List<WebSocketUserDialogue> webSocketUserDialogues = webSocketUserDialogueMapper.selectList(webSocketUserDialogueQueryWrapper);
        for (WebSocketUserDialogue webSocketUserDialogue : webSocketUserDialogues) {
            UserFriendVO userFriendVO = new UserFriendVO();
            userFriendVO.setDialogueId(webSocketUserDialogue.getId());
            if (webSocketUserDialogue.getType() == 0) {//一对一单聊
                userFriendVO.setType(0);
                if (webSocketUserDialogue.getAUserId() == SecurityUtils.getUserId()) {//判定对话框中的自己时在A中，那B就是好友
                    SysUser sysUser = sysUserMapper.selectUserById(webSocketUserDialogue.getBUserId());
                    userFriendVO.setUserId(webSocketUserDialogue.getBUserId());
                    QueryWrapper<WebSocketGroupUser> webSocketGroupUserQueryWrapper = new QueryWrapper<>();
                    webSocketGroupUserQueryWrapper.eq("user_id", webSocketUserDialogue.getBUserId());
                    webSocketGroupUserQueryWrapper.eq("user_name", webSocketUserDialogue.getBUserName());
                    webSocketGroupUserQueryWrapper.eq("dialogue_id", webSocketUserDialogue.getId());
                    webSocketGroupUserQueryWrapper.eq("type", 0);
                    WebSocketGroupUser webSocketGroupUser = webSocketGroupUserMapper.selectOne(webSocketGroupUserQueryWrapper);
                    if (null != webSocketGroupUser) {
                        userFriendVO.setFunctionId(webSocketGroupUser.getId());
                    }
                    if (null != webSocketGroupUser && null != webSocketGroupUser.getTopUp() && !webSocketGroupUser.getTopUp().equals("")) {
                        userFriendVO.setTopUp(webSocketGroupUser.getTopUp() + "/B");
                    } else {
                        userFriendVO.setTopUp("0/B");
                    }
                    if (null != webSocketGroupUser && null != webSocketGroupUser.getDisturb() && !webSocketGroupUser.getDisturb().equals("")) {
                        userFriendVO.setDisturb(webSocketGroupUser.getDisturb() + "/B");
                    } else {
                        userFriendVO.setDisturb("0/B");
                    }
                    userFriendVO.setAvatar(sysUser.getAvatar());
                    userFriendVO.setName(webSocketUserDialogue.getBUserName());
                    if (null != webSocketUserDialogue.getBUserRemarks() && !webSocketUserDialogue.getBUserRemarks().equals("")) {
                        userFriendVO.setUserRemarks(webSocketUserDialogue.getBUserRemarks() + "/B");
                    }
                    if (null != webSocketGroupUser && null != webSocketGroupUser.getRemarks() && !webSocketGroupUser.getRemarks().equals("")) {
                        userFriendVO.setUserRemarks(webSocketGroupUser.getRemarks() + "/B");
                    }
                } else {//相反
                    SysUser sysUser = sysUserMapper.selectUserById(webSocketUserDialogue.getAUserId());
                    if (null != sysUser && null != sysUser.getAvatar()) {
                        userFriendVO.setAvatar(sysUser.getAvatar());
                    }

                    userFriendVO.setUserId(webSocketUserDialogue.getAUserId());
                    QueryWrapper<WebSocketGroupUser> webSocketGroupUserQueryWrapper = new QueryWrapper<>();
                    webSocketGroupUserQueryWrapper.eq("user_id", webSocketUserDialogue.getAUserId());
                    webSocketGroupUserQueryWrapper.eq("user_name", webSocketUserDialogue.getAUserName());
                    webSocketGroupUserQueryWrapper.eq("dialogue_id", webSocketUserDialogue.getId());
                    webSocketGroupUserQueryWrapper.eq("type", 0);
                    WebSocketGroupUser webSocketGroupUser = webSocketGroupUserMapper.selectOne(webSocketGroupUserQueryWrapper);
                    if (null != webSocketGroupUser) {
                        userFriendVO.setFunctionId(webSocketGroupUser.getId());
                    }
                    if (null != webSocketGroupUser && null != webSocketGroupUser.getTopUp() && !webSocketGroupUser.getTopUp().equals("")) {
                        userFriendVO.setTopUp(webSocketGroupUser.getTopUp() + "/A");
                    } else {
                        userFriendVO.setTopUp("0/A");
                    }
                    if (null != webSocketUserDialogue.getBUserRemarks() && !webSocketUserDialogue.getBUserRemarks().equals("")) {
                        userFriendVO.setUserRemarks(webSocketUserDialogue.getAUserRemarks() + "/A");
                    }
                    userFriendVO.setName(webSocketUserDialogue.getAUserName());
                    if (null != webSocketGroupUser && null != webSocketGroupUser.getRemarks() && !webSocketGroupUser.getRemarks().equals("")) {
                        userFriendVO.setUserRemarks(webSocketGroupUser.getRemarks() + "/A");
                    }
                    if (null != webSocketGroupUser && null != webSocketGroupUser.getDisturb() && !webSocketGroupUser.getDisturb().equals("")) {
                        userFriendVO.setDisturb(webSocketGroupUser.getDisturb() + "/A");
                    } else {
                        userFriendVO.setDisturb("0/A");
                    }
                }
            } else if (webSocketUserDialogue.getType() == 1){//群聊
                System.out.println(webSocketUserDialogue.getId());
                SysUser sysUser = sysUserMapper.selectUserById(webSocketUserDialogue.getCreateId());
                String[] split = webSocketUserDialogue.getGroupUser().split(",");
                List<Map> maps = new ArrayList<>();
                if (split.length > 0) {
                    for (String userName : split) {
                        Map<String, String> stringStringHashMap = new HashMap<>();
                        String userNameUrl = sysUserMapper.selectNameUrl(userName);
                        SysUser sysUser1 = sysUserMapper.selectUserByUserName(userName);
                        if (userNameUrl == null) {
                            userNameUrl = "http://119.91.22.164:8085/images/defaultBoy.png";
                        }
                        stringStringHashMap.put("userName", userName);
                        stringStringHashMap.put("avatar", userNameUrl);
                        if (sysUser1 == null) {
                            stringStringHashMap.put("nickName", "此账户已删除");
                        } else {
                            stringStringHashMap.put("nickName", sysUser1.getNickName());
                        }

                        maps.add(stringStringHashMap);
                    }
                }
                QueryWrapper<WebSocketGroupUser> webSocketGroupUserQueryWrapper = new QueryWrapper<>();
                webSocketGroupUserQueryWrapper.eq("user_id", userId);
                webSocketGroupUserQueryWrapper.eq("user_name", username);
                webSocketGroupUserQueryWrapper.eq("dialogue_id", webSocketUserDialogue.getId());
                webSocketGroupUserQueryWrapper.eq("type", 1);
                WebSocketGroupUser webSocketGroupUser = webSocketGroupUserMapper.selectOne(webSocketGroupUserQueryWrapper);
                if (null != webSocketGroupUser) {
                    userFriendVO.setFunctionId(webSocketGroupUser.getId());
                }
                if (null != webSocketGroupUser && null != webSocketGroupUser.getTopUp() && !webSocketGroupUser.getTopUp().equals("")) {
                    userFriendVO.setTopUp(webSocketGroupUser.getTopUp().toString());
                } else {
                    userFriendVO.setTopUp("0");
                }
                userFriendVO.setUserNameUrl(maps);
                if (null != sysUser && null != sysUser.getAvatar()) {
                    userFriendVO.setAvatar(sysUser.getAvatar());
                }

                userFriendVO.setType(1);
                userFriendVO.setName(webSocketUserDialogue.getGroupName());
                userFriendVO.setUserRemarks(webSocketUserDialogue.getGroupRemarks());
                if (null != webSocketGroupUser && null != webSocketGroupUser.getRemarks() && !webSocketGroupUser.getRemarks().equals("")) {
                    userFriendVO.setUserRemarks(webSocketGroupUser.getRemarks());
                }
                if (null != webSocketGroupUser && null != webSocketGroupUser.getDisturb() && !webSocketGroupUser.getDisturb().equals("")) {
                    userFriendVO.setDisturb(webSocketGroupUser.getDisturb().toString());
                } else {
                    userFriendVO.setDisturb("0");
                }
                userFriendVO.setGroupUser(webSocketUserDialogue.getGroupUser());
                userFriendVO.setCreateId(webSocketUserDialogue.getCreateId());
                userFriendVO.setGroupNotice(webSocketUserDialogue.getGroupNotice());
                SysUser createUser = sysUserMapper.selectUserById(webSocketUserDialogue.getCreateId());
                userFriendVO.setGroupCreateByName(createUser.getUserName());
            }else if (webSocketUserDialogue.getType() == 3){
//                临时
                if (webSocketUserDialogue.getAUserId() == SecurityUtils.getUserId()) {//判定对话框中的自己时在A中，那B就是好友
                    SysUser sysUser = sysUserMapper.selectUserById(webSocketUserDialogue.getBUserId());
                    userFriendVO.setUserId(webSocketUserDialogue.getBUserId());
                    userFriendVO.setAvatar(sysUser.getAvatar());
                    userFriendVO.setName(webSocketUserDialogue.getBUserName());
                    userFriendVO.setType(3);
                    if (null != webSocketUserDialogue.getBUserRemarks() && !webSocketUserDialogue.getBUserRemarks().equals("")) {
                        userFriendVO.setUserRemarks(webSocketUserDialogue.getBUserRemarks());
                    }
                } else if(webSocketUserDialogue.getBUserId() == SecurityUtils.getUserId()){//相反
                    SysUser sysUser = sysUserMapper.selectUserById(webSocketUserDialogue.getAUserId());
                    if (null != sysUser && null != sysUser.getAvatar()) {
                        userFriendVO.setAvatar(sysUser.getAvatar());
                        userFriendVO.setName(sysUser.getUserName());
                        userFriendVO.setType(3);
                    }
                    if (null != webSocketUserDialogue.getBUserRemarks() && !webSocketUserDialogue.getBUserRemarks().equals("")) {
                        userFriendVO.setUserRemarks(webSocketUserDialogue.getAUserRemarks());
                    }
                    userFriendVO.setUserId(webSocketUserDialogue.getAUserId());
                }
                userFriendVO.setTopUp("0");
            }
            userFriendVOS.add(userFriendVO);
        }
        userFriendVOS.sort(Comparator.comparing(UserFriendVO::getTopUp).reversed());
        if (null != message && !message.equals("")) {
            userFriendVOS = userFriendVOS.stream().filter(w -> w.getUserRemarks().contains(message)).collect(Collectors.toList());
        }

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", userFriendVOS);
    }

    @Override
    public AjaxResult addGroupUser(WebSocketUserDialogue webSocketUserDialogue) {
        String[] groupUsers = webSocketUserDialogue.getGroupUser().split(",");
        if (!StringUtils.hasText(webSocketUserDialogue.getGroupUser())) {
            return new AjaxResult(HttpStatus.ERROR, "请选择群成员!!!");
        }
        if (groupUsers.length> 199){
            return new AjaxResult(HttpStatus.ERROR, "群聊人数不能超过200");
        }
        String username = SecurityUtils.getUsername();
        Long userId = SecurityUtils.getUserId();
        webSocketUserDialogue.setCreateId(userId);
        webSocketUserDialogue.setType(1);
        webSocketUserDialogue.setGroupNotice("这里可以添加群公告！！！");
        webSocketUserDialogue.setGroupUser(webSocketUserDialogue.getGroupUser() + "," + username);
        Integer insert = webSocketUserDialogueMapper.insert(webSocketUserDialogue);
        if (insert == 0) {
            return new AjaxResult(HttpStatus.ERROR, "创建失败");
        }
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功");
    }

    private Lock lock = new ReentrantLock();

    @Override
    @Transactional
    public AjaxResult deleteGroupUser(Integer dialogueId, String userName, Integer type) {
        lock.lock();
        try {
            Long userId = SecurityUtils.getUserId();
            String username = SecurityUtils.getUsername();
            WebSocketUserDialogue webSocketUserDialogue = webSocketUserDialogueMapper.selectById(dialogueId);
            if (null != webSocketUserDialogue.getGroupUser() && !webSocketUserDialogue.getGroupUser().equals("")) {
                String groupUsers = webSocketUserDialogue.getGroupUser();
                String[] split = webSocketUserDialogue.getGroupUser().split(",");
                if (type == 1) {//删除或者退出群聊
                    if (split.length <= 2) {
                        webSocketUserDialogueMapper.deleteById(dialogueId);
                        List<Integer> list = webSocketMessageMapper.selectByDialogueId(dialogueId);
                        if (!CollectionUtils.isEmpty(list)) {
                            int i = webSocketMessageMapper.deleteBatchIds(list);
                            if (i == 0) {
                                return new AjaxResult(HttpStatus.ERROR, "群聊天记录删除失败");
                            }
                        }
                        return new AjaxResult(HttpStatus.SUCCESS, "操作成功，群聊已经解散");

                    } else {
                        for (String s : split) {
                            if (s.equals(userName)) {
                                String oldGroupUser = "," + webSocketUserDialogue.getGroupUser() + ",";
                                String groupUser = oldGroupUser.replaceAll("," + userName + ",", ",");
                                String newGroupUser = groupUser.substring(1, groupUser.length() - 1);
                                webSocketUserDialogue.setGroupUser(newGroupUser);

//                                String oldGroupName = "," + webSocketUserDialogue.getGroupName() + ",";
//                                String groupUserName = oldGroupName.replaceAll("," + userName + ",", ",");
//                                String newGroupUserName = groupUserName.substring(1, groupUser.length() - 1);
//                                webSocketUserDialogue.setGroupName(newGroupUserName);

//                                String oldGroupRemarks = "," + webSocketUserDialogue.getGroupRemarks() + ",";
//                                String groupUserRemarks = oldGroupRemarks.replaceAll("," + username + ",", ",");
//                                String newGroupUserRemarks = groupUserRemarks.substring(1, groupUser.length() - 1);
//                                webSocketUserDialogue.setGroupRemarks(newGroupUserRemarks);


                                webSocketUserDialogueMapper.updateById(webSocketUserDialogue);
                                return new AjaxResult(HttpStatus.SUCCESS, "退出成功");
                            }
                        }
                    }
                } else if (type == 2 && null != userName) {

                    String[] split1 = webSocketUserDialogue.getGroupUser().split(",");
                    String[] split2 = userName.split(",");
                    if (split2.length+split1.length > 199){
                        return new AjaxResult(HttpStatus.ERROR, "群聊人数不能超过200");
                    }

//                    if (split2.length>0){
//                        for (String s :split2) {
//                            groupUsers.contains(s);
//                        }
//                    }
//                    for (String s : split) {
//                        if (s.equals(userName)) {
//                            return new AjaxResult(HttpStatus.SUCCESS, userName+"已经在该群聊中，请勿重复添加。。。");
//                        }
//                    }
                    SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
                    String newGroupUser = webSocketUserDialogue.getGroupUser() + "," + userName;
                    webSocketUserDialogue.setGroupUser(newGroupUser);
//                    webSocketUserDialogue.setBUserName(webSocketUserDialogue.getGroupName() + "," + sysUser.getUserName());
//                    webSocketUserDialogue.setGroupRemarks(webSocketUserDialogue.getGroupRemarks() + "," + sysUser.getUserName());
                    webSocketUserDialogueMapper.updateById(webSocketUserDialogue);
                    return new AjaxResult(HttpStatus.SUCCESS, "添加成功");
                } else if (type == 3) {
                    if (webSocketUserDialogue.getCreateId().toString().equals(userId.toString())) {
                        webSocketUserDialogueMapper.deleteById(dialogueId);
                        List<Integer> list = webSocketMessageMapper.selectByDialogueId(dialogueId);
                        if (!CollectionUtils.isEmpty(list)) {
                            int i = webSocketMessageMapper.deleteBatchIds(list);
                            if (i == 0) {
                                return new AjaxResult(HttpStatus.ERROR, "群聊天记录删除失败");
                            }
                        }
                        return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
                    } else {
                        return new AjaxResult(HttpStatus.ERROR, "请群主删除");
                    }

                }
            }
            return new AjaxResult(HttpStatus.ERROR, "请传递正确参数");
        } catch (Exception e) {
            //打印异常
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
        return new AjaxResult(HttpStatus.ERROR, "群组数据问题，请联系管理员");
    }


    @Override
    @Transactional
    public AjaxResult deleteUser(Integer dialogueId) {
        Long userId = SecurityUtils.getUserId();
        WebSocketUserDialogue webSocketUserDialogue = webSocketUserDialogueMapper.selectById(dialogueId);
        if (webSocketUserDialogue.getBUserId().toString().equals(userId.toString())) {
            webSocketUserApplicationMapper.deleteWebSocketUserApplication(webSocketUserDialogue.getAUserId(), userId);
        } else if (webSocketUserDialogue.getAUserId().toString().equals(userId.toString())) {
            webSocketUserApplicationMapper.deleteWebSocketUserApplication(userId, webSocketUserDialogue.getBUserId());
        }
        QueryWrapper<WebSocketGroupUser> webSocketGroupUserQueryWrapper = new QueryWrapper<>();
        webSocketGroupUserQueryWrapper.eq("dialogue_id", dialogueId);
        webSocketGroupUserMapper.delete(webSocketGroupUserQueryWrapper);
        webSocketUserDialogueMapper.deleteById(dialogueId);
        List<Integer> list = webSocketMessageMapper.selectByDialogueId(dialogueId);
        if (!CollectionUtils.isEmpty(list)) {
            int i = webSocketMessageMapper.deleteBatchIds(list);
            if (i == 0) {
                return new AjaxResult(HttpStatus.ERROR, "私聊聊记录删除失败");
            }
        }
        return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
    }

    @Override
    public AjaxResult updateGroupDetail(Map<String, Object> map) {
        Long userId = SecurityUtils.getUserId();
        Long createId = Long.parseLong(map.get("createId").toString());
        Integer dialogueId  = Integer.parseInt(map.get("dialogueId").toString());
        WebSocketUserDialogue webSocketUserDialogue = webSocketUserDialogueMapper.selectById(dialogueId);
        if (userId != webSocketUserDialogue.getCreateId()){
            return new AjaxResult(HttpStatus.ERROR, "群主才能修改");
        }
        if (webSocketUserDialogue.getType() == 1) {
            if (StringUtils.hasText((String) map.get("groupNotice"))) {
                webSocketUserDialogue.setGroupNotice((String) map.get("groupNotice"));
            }
            if (StringUtils.hasText((String) map.get("groupName"))){
                webSocketUserDialogue.setGroupName((String) map.get("groupName"));
            }
            webSocketUserDialogueMapper.updateById(webSocketUserDialogue);
        }
        return new AjaxResult(HttpStatus.SUCCESS, "群信息修改完成",webSocketUserDialogue);
    }
}
